<?php

namespace app\admin\controller\statistics;

use app\admin\model\develop\Acuisitionscheme;
use app\admin\model\entrepot\Deliver;
use app\common\controller\Backend;
use think\Db;
use think\db\Connection;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 物料方案
 *
 * @icon fa fa-circle-o
 */
class Materialplanaudit extends Backend
{

    /**
     * Materialplan模型对象
     * @var \app\admin\model\statistics\Materialplan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\statistics\Materialplanaudit();
        $this->view->assign("attributeList", $this->model->getAttributeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $type = $this->request->request('type');
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = [];
            if ($type == 'dashboard') $where2['attribute'] = 1;

            $list = $this->model
                ->with(['colour','admin','createuser'])
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'trademark_printing', 'abbreviation', 'finished_weight', 'feeding_weight', 'attrition_rate', 'attribute', 'name', 'materiallist', 'status','audittime']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['createuser']);
                $row->getRelation('createuser')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 物料方案审核
     * @return void
     */
    public function audit($ids = null)
    {
        set_time_limit(0);
        $row = $this->model->get(['id' => $ids, 'status' => ['neq', 1]]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (!isset($params['status'])) $this->error('参数错误');
            $flag = true;

            Db::startTrans();
            //更新方案状态
            $upData['operator_uid'] = $this->auth->id;
            $upData['audittime'] = time();
            $upData['status'] = $params['status'];

            $setStatus = $this->model->where('id', 'eq', $ids)->update($upData);
//            p($this->model->where('id', 'eq', $ids)->fetchSql()->update($upData));
            if ($setStatus) {
                $materialPlan = new \app\admin\model\statistics\Materialplan();

                if ($params['status'] == 1) {
                    //更新物料方案表状态为1已处理
                    $upMaterialPlanData = $row->toArray();
                    $upMaterialPlanData['status'] = 1;
                    $upMaterialPlanData['id'] = $upMaterialPlanData['pid'];

                    $materialPlan->allowField(true)->isUpdate(true)->save($upMaterialPlanData);

//                    $magerialPlanData = $materialPlan->get(['id' => $row['pid']]);
//                    p(create_order_acuisitionscheme($row));
                    create_order_acuisitionscheme($row);

//                    if (!$res2){
//                        Db::rollback();
//                        $this->error('操作失败');
//                    }
//                    $flag = $res && $res2;
                } else {
                    //更新物料方案表状态为3审核驳回
                    $res = $materialPlan->where('id', 'eq', $row['pid'])->setField('status', 3);
                    if (!$res) $flag = false;
                }
            } else {
                $flag = false;
            }
            if ($flag == true) {
                Db::commit();
                $this->success('操作成功');
            } else {
                Db::rollback();
                $this->error('审核失败');
            }

        }
        if ($this->request->isGet()) {
            $row['colour_name'] = Db::name('colour')->where('id="' . $row['colour_id'] . '"')->value('name');
            $this->view->assign("row", $row);
            return $this->view->fetch('statistics/materialplanaudit/audit');
        }
    }

    public function getMaterialColourName()
    {
        $res = getSelectPage('material_colour', 'name');
        return $res;
    }

    public function getMaterialName()
    {
        $res = getSelectPage('material', 'name');
        return $res;
    }

    public function get_material_plan()
    {
        $res = getSelectPage('material_plan', 'attribute');
        return $res;
    }
}
